<template>
  <div class="default-main ba-table-box">
    <!-- 表格顶部菜单 -->
    <TableHeader
      :buttons="['refresh', 'add', 'remove', 'comSearch', 'columnDisplay']"
      :quick-search-placeholder="placeholder"
      @action="baTable.onTableHeaderAction"
    />
    <!-- 表格 -->
    <!-- 要使用`el-table`组件原有的属性，直接加在Table标签上即可 -->
    <Table ref="tableRef" @action="baTable.onTableAction" />
    <!-- 表单 -->
    <PopupForm v-if="baTable.form.operate ? true : false" />
  </div>
</template>
<script setup lang="ts">
import { ref, provide, onMounted, markRaw } from "vue";
import baTableClass from "@/utils/baTable";
import { baTableApi, operatorShowOff, getDictData } from "@/utils/common"; // 导入表格api方法生成器
import { WorkOrder } from "@/api/backend/index";
import Table from "@/components/table/index.vue";
import TableHeader from "@/components/table/header/index.vue";
import PopupForm from "./popupForm.vue";
import { useRoute, useRouter } from "vue-router";
import useCurrentInstance from "@/utils/useCurrentInstance";
import type { TableRow, TableColumn } from "@/utils/baTable"; //表格列行类型
import { useProject } from "@/store/backend/ServiceM/project";
//   import { useScope } from "@/store/backend/erpM/scope";
//   import { useService } from "@/store/backend/ServiceM/service";
import { useStaff } from "@/store/backend/ServiceM/staff";
import { useBusiness } from "@/store/backend/BusinessM/info";
import { useAccess } from "@/store/backend/DeviceM/access";
import { useWorkOrder } from "@/store/backend/WorkOrder/order";
import TagState from "@/components/dictTagState/index.vue";
import TagSearch from "@/components/tagSearch/index.vue";
import { useDictionary } from "@/store/backend/tool/dictionary";
import DateTime from "@/components/datePicker/index.vue";
import { useNavTabs } from "@/store/navTabs";

var timer: NodeJS.Timer;

const placeholder = ref<string>("模糊搜索");
const tableRef = ref();
const route = useRoute();
const router = useRouter();
const project = useProject();
//   const scope = useScope();
//   const service = useService();
const staff = useStaff();
const business = useBusiness();
const access = useAccess();
const order = useWorkOrder();
const dictionary = useDictionary();
const navTabs = useNavTabs();

//字段显隐记忆功能
const filedShowOff = (filter: any) => {
  if ((navTabs as any).columnDisplayStoreMap) {
    return (navTabs as any).columnDisplayStoreMap.get(
      route.path + "/" + filter
    );
  }
  return true;
};
// 字段显隐记忆功能 字段中有默认隐藏false情况的
const filedShowOffDefault = (filter: any) => {
  if ((navTabs as any).columnDisplayStoreMap) {
    return (navTabs as any).columnDisplayStoreMap.get(route.path + "/" + filter)
      ? true
      : false;
  }
  return "";
};
// 每页个数记忆功能
const pageSizeKeep = () => {
  if ((navTabs as any).pageSizeMap) {
    return (navTabs as any).pageSizeMap.get(route.path + WorkOrder)
      ? (navTabs as any).pageSizeMap.get(route.path + WorkOrder)
      : 10;
  }
  return 10;
};

const baTable = new baTableClass(
  new baTableApi(WorkOrder), //this.api = api部门管理
  {
    expandAll: true,
    pk: "id",
    column: [
      { type: "selection", align: "center", operator: false },
      {
        show: filedShowOff("workinforNumber"),
        label: "工单编号",
        prop: "workinforNumber",
        align: "left",
        fixed: "left",
        operatorPlaceholder: "模糊搜索",
      },
      {
        show: filedShowOff("status"),
        label: "工单状态",
        prop: "status",
        align: "center",
        fixed: "left",
        width: "80",
        render: "customRender",
        customRender: markRaw(TagState),
        comSearchRender: "customRender",
        comSearchCustomRender: markRaw(TagSearch),
        // // render: "switch",
        // render: "tag",
        // custom: { 0: "danger", 1: "info", 2: "warning", 3: "success" },
        // replaceValue: {
        //   0: "待派单",
        //   1: "已派单",
        //   2: "服务中",
        //   3: "已完成",
        // },
      },
      {
        show:
          filedShowOffDefault("deviceAddress") === ""
            ? false //默认false
            : filedShowOffDefault("deviceAddress"),
        label: "设备地址",
        prop: "deviceAddress",
        align: "left",
        fixed: "left",
        operator: false,
      },
      {
        show: filedShowOff("projectName"),
        label: "项目名称",
        prop: "projectName",
        align: "left",
        operator: false,
      },
      {
        show: filedShowOff("customerName"),
        label: "服务企业名称",
        prop: "customerName",
        align: "left",
        operatorPlaceholder: "模糊搜索",
      },
      {
        show: filedShowOff("startTime"),
        label: "服务开始时间",
        prop: "startTime",
        align: "left",
        operator: false,
      },
      {
        show: filedShowOff("endTime"),
        label: "服务完成时间",
        prop: "endTime",
        align: "left",
        operator: false,
      },
      {
        show: filedShowOff("employeeName"),
        label: "维护人员",
        prop: "employeeName",
        align: "left",
      },
      {
        show: filedShowOff("chargePerson"),
        label: "主修人",
        prop: "chargePerson",
        align: "left",
      },
      {
        show: filedShowOff("createTime"),
        label: "申请服务时间",
        prop: "createTime",
        align: "center",
        comSearchRender: "customRender",
        comSearchCustomRender: markRaw(DateTime),
      },
      {
        show: operatorShowOff([
          route.path + "/edit",
          route.path + "/add",
          route.path + "/remove",
        ]),
        label: "操作",
        align: "center",
        width: "130",
        operator: false,
        render: "buttons",
        fixed: "right",
        buttons: [
          {
            render: "tipButton",
            name: "edit",
            title: "编辑",
            text: "",
            type: "primary",
            icon: "fa fa-pencil",
            class: "table-row-edit",
            disabledTip: false,
            // 按钮是否显示，请返回布尔值
            display: (row: TableRow, field: TableColumn) => {
              return true;
            },
            // 按钮是否禁用，请返回布尔值
            disabled: (row: TableRow, field: TableColumn) => {
              return false;
            },
            attr: {},
          },
          {
            render: "confirmButton",
            name: "remove",
            title: "删除",
            text: "",
            type: "danger",
            icon: "el-icon-DeleteFilled",
            class: "table-row-delete",
            popconfirm: {
              confirmButtonText: "删除",
              cancelButtonText: "取消",
              confirmButtonType: "danger",
              title: "确定删除所选项吗",
            },
            disabledTip: false,
            // 按钮是否显示，请返回布尔值
            display: (row: TableRow, field: TableColumn) => {
              return true;
            },
            // 按钮是否禁用，请返回布尔值
            disabled: (row: TableRow, field: TableColumn) => {
              return false;
            },
            attr: {},
          },
          {
            render: "tipButton",
            name: "info",
            title: "详情",
            text: "",
            type: "primary",
            icon: "fa fa-search-plus",
            class: "table-row-edit",
            disabledTip: false,
            // 按钮是否显示，请返回布尔值
            display: (row: TableRow, field: TableColumn) => {
              return true;
            },
            // 按钮是否禁用，请返回布尔值
            disabled: (row: TableRow, field: TableColumn) => {
              return false;
            },
            attr: {},
          },
        ],
      },
    ],
    filter: {
      pageSize: pageSizeKeep(),
      // providerId: service.roles.includes("provider") ? service.providerId : "",
      // employeeId: service.roles.includes("employee") ? staff.employeeId : "",
    },
  },
  {
    defaultItems: {
      status: "1", //pc端工单发起为待执行
    },
  }
);

//跳转工单详情页
const infoButtonClick = (name: string, row: any) => {
  console.log("row跳转工单详情页", row);
  order.$patch((state) => {
    state.single = row;
  });
  router.push({
    path: "/admin/WorkOrder/detail",
  });
};

//获取工单状态的字典
const getMenuStatus = () => {
  dictionary.getDictInfo("sys_workorder_status").then((res: any) => {
    dictionary.tag = getDictData(res);
    console.log("获取工单状态的字典", dictionary.tag);
  });
};
getMenuStatus();

onMounted(() => {
  //全局事件总线
  const { proxy } = useCurrentInstance();
  //将table的ref给到table类
  baTable.table.ref = tableRef.value;
  baTable.mount();
  baTable.getList(WorkOrder);
  /**
   * 表格内的按钮响应
   * @param name 按钮name
   * @param row 被操作行数据
   */
  proxy.eventBus.on(
    "onTableButtonClick",
    (data: { name: string; row: TableRow }) => {
      if (!baTable.activate) return;
      if (data.name == "info") {
        //携带主键字段pk
        infoButtonClick(
          (data.row as TableRow)[baTable.table.pk!],
          data.row as any
        );
      }
    }
  );
});

// 实例化表格后，将 baTable 的实例提供给上下文
provide("baTable", baTable);
provide("project", project);
//   provide("scope", scope);
//   provide("service", service);
provide("staff", staff);
provide("business", business);
provide("access", access);
provide("dictionary", dictionary);
</script>
<style lang="scss" scoped>
.default-main {
  margin: var(--ba-main-space) var(--ba-main-space) 60px var(--ba-main-space);
}
</style>
